﻿$(document).ready(function () {
    //show the badges and items of NeedFulfil and NeedAccept
    if (typeof $.cookie("UserId") != 'undefined') {
        $.ajax({
            url: "/Message/_HasNew",
            dataType: "json",
            cache: false,
            success: function (data) {
                if (data) {
                    $("#hasNewMessage").show();
                    setInterval(function () {
                        if ($("#message").attr("style") == "color: white;") {
                            $("#message").attr("style", "color: gray");
                        } else {
                            $("#message").attr("style", "color: white");
                        }
                    }, 800)
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AjaxError("/Message/_HasNew", textStatus, errorThrown)
            }
        });

        $.ajax({
            url: "/Task/_NeedFulfil",
            dataType: "json",
            cache: false,
            success: function (data) {
                if (data.items != null
                    && data.items.length > 0) {
                    $("#need_fulfil .badge").text(data.items.length);
                    for (var i = 0; i < data.items.length; i++) {
                        $item = '<li><a href="/Task/Fulfil/'
                            + data.items[i].Id
                            + '"> '
                            + (i + 1) + '#  ' + data.items[i].Name
                            + '</a></li>';
                        $($item).insertBefore($("#need_fulfil .dropdown-menu").children().last())
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AjaxError("/Task/_NeedFulfil", textStatus, errorThrown)
            }
        });

        $.ajax({
            url: "/Task/_NeedAccept",
            dataType: "json",
            cache: false,
            success: function (data) {
                if (data.items != null
                    && data.items.length > 0) {
                    $("#need_accept .badge").text(data.items.length);
                    for (var i = 0; i < data.items.length; i++) {
                        $item = '<li><a href="/Task/Accept/'
                            + data.items[i].Id
                            + '"> '
                            + (i + 1) + '#  ' + data.items[i].Name
                            + '</a></li>';
                        $($item).insertBefore($("#need_accept .dropdown-menu").children().last())
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AjaxError("/Task/_NeedAccept", textStatus, errorThrown)
            }
        });

        $("input[type='checkbox'][name='message_known']").click(function () {
            var url = "/Message/_Read/" + $(this).val();
            var $trigger = $(this);
            var $container = $trigger.parentsUntil(".plane");
            $.ajax({
                url: url,
                cache: false,
                success: function (data) {
                    $trigger.parent().remove();
                    $container.removeClass("panel-primary").addClass("panel-default");
                    ;
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    AjaxError(url, textStatus, errorThrown)
                }
            });
        })

        $("#apply-leave").click(function (event) {
            event.preventDefault();
            var selectedDayNumber = $("input[name='TaskItem.CompleteDate']:checked").length;
            if (selectedDayNumber == 0) {
                $("#atLeastOneDay").text("* 请选择一个请假时间");
                return false;
            }
            url = $(this).attr("href");
            $.ajax({
                url: url,
                dataType: "json",
                type: "POST",
                data: $('form').serialize(),
                cache: false,
                success: function (canLeave) {
                    if (!canLeave) {
                        alert("No,No,No, 该目标本周假期已经用完了哟！");
                    } else {
                        location.reload();
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    AjaxError(url, textStatus, errorThrown)
                }
            });

        })
    }

    //show the page's introduction modal
    $(".show_introduction").click(function () {
        $modal = $("#page_introduction_modal");
        $modal.find(".modal-title")
            .text($("#page_introduction h3").text());
        $modal.find(".modal-body")
            .html($("#page_introduction_body").html());
        $modal.modal("show");
    });

    $('.panel-body[id^="plan_detail_"]').on('shown.bs.collapse', function () {
        var $container = $(this);
        var id = $container.attr("id").substr(12); /* 11 = 'plan_detail_'.lengh()*/

        $.ajax({
            url: "/Plan/_ShowItemBody/" + id,
            dataType: "html",
            cache: false,
            success: function (data) {
                $container.html(data);
                $(".show_link").click(function () {
                    var $showUrl = $(this).parent().parent().find(".show_plan_url");
                    $showUrl.show();
                })
                //join the plan
                $("a[join_plan_id]").click(function (event) {
                    event.preventDefault();
                    if (!hasLogon()) {
                        alert("你还没有登录吧？需要登录了才能加入哟。");
                        location.href = "/Log/On?prepage="
                            + encodeURIComponent(location.pathname + location.search);
                        return false;
                    }
                    var id = $(this).attr("join_plan_id");
                    var $trigger = $(this);
                    $.ajax({
                        url: "/Plan/_Join/" + id,
                        dataType: "html",
                        success: function (data) {
                            var $modalButton = $("#result .modal-footer");
                            $modalButton.prevAll().remove();
                            $modalButton.before(data);
                            $trigger.remove();
                            $('#result').modal();
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            AjaxError("/Plan/_Join/" + id, textStatus, errorThrown)
                        }
                    });
                });
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AjaxError("/Plan/_ShowItemBody/" + id, textStatus, errorThrown)
            }
        });
    });

    $("span[data-taskday-id]").click(function () {
        var taskId = $(this).attr("data-taskday-id");
        if (taskId == 0) {
            $('#day-history-content').html(
                "<div style='padding: 20px'>" +
                    "<img alt='sorry' title='sorry' src='/Image/sorry.png' /> " +
                    "这一天你没有提交任务！" +
                "</div>"
            );
            $('#day-history').modal();
        }
        else {
            var url = "/Task/_HistoryItem?taskId=" + taskId;
            $('#day-history-content').html("");
            var $trigger = $(this);
            $trigger.hide();
            $.ajax({
                url: url,
                dataType: "html",
                success: function (data) {
                    $trigger.show();
                    $('#day-history-content').html(data);
                    $('#day-history').modal();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    AjaxError(url, textStatus, errorThrown)
                }
            });
        }
    })
})



function AjaxError(url, textStatus, errorThrown) {
    alert("咦？Ajax调用：" + url + " 时出现错误。\r\n"
        + "该错误服务器可能无法侦测。如果问题反复出现，请联系我们。\r\n"
        + "这将有助于我们提高系统质量，万分感谢您的支持和帮助！\r\n"
        + "textStatus：" + textStatus + "\r\n"
        + "errorThrown：" + errorThrown + "\r\n"
        );
}

function hasLogon() {
    return typeof $.cookie("UserId") != 'undefined';
}
